var $ = window.$;
var jade = require('jade');
var config = require('../../core/config');
var event = require('../../core/event');
var uiUtil = require('../../util/ui');
var timing = require('../timing/manager');
var io = require('../io/ui');
var sound = require('../audio/sound');
var animate = require('../../util/animate');
var note = require('../note/manager');
var sample = require('../sample/manager');
var grid = require('../grid/manager');
var path = require('path');
var notify = require('../notify/ui');

var _inited = false;

var ret = {
    init: function() {
        if (_inited) {
            return;
        }
        this.playId = -1;
        this.playCell = -1;
        event.bind(event.events.dialog.editmusic, 'bgm_edit', this);
        event.lock('key', 'bgm_edit');
        _inited = true;
    },

    bindUIEvent : function(){
        var self = this;
        this.parent.on('click','.g_click', function() {
            var type = $(this).data('type');
            if (type == 'close') {
                self.hide();
                return;
            }else if(type == "accept"){
                self.updateMusicInfo();
                self.hide();
                return;
            }else if (type == 'load') {
                io.getSoundPath().then(function (file) {
                    if (!file || file == self.audioFile) {
                        return;
                    }
                    if (self.audioFile) {
                        self.stopMusic(true);
                    }
                    self.audioFile = file;
                    self.parent.find("#dialog_timing_title").html(path.basename(file));
                    self.lock = false;
                });
                return;
            }else if(type == 'play'){
                if(!self.audioFile){
                    return;
                }
                sound.fmod.selectTrack(1);
                if(self.playId != -1){
                    sound.fmod.playTrack();
                }else{
                    self.playId = sound.load(self.audioFile);
                    if(self.playId == -1){
                        notify.addNotify({
                            msg: config.i18n("err01")
                        });
                        return;
                    }
                    sound.fmod.selectAudio(self.playId);
                    self.playCell = sound.fmod.addCell();
                    sound.fmod.offsetCell(0);
                    sound.fmod.volumeCell(30);
                    var len = sound.fmod.lengthAudio();
                    sound.fmod.setLenTrack(len);
                    sound.fmod.playTrack();
                }
            }else if(type == 'stop'){
                if(self.playId == -1){
                    return;
                }
                self.stopMusic(false);
            }
        });
    },

    show : function(){
        if(this.parent){
            return;
        }
        var bgmNote = this.findBgmNote();
        if(!bgmNote){
            notify.addNotify({
                msg: config.i18n("err24")
            });
            return;
        }
        var tmpl = jade.compileFile('./tmpl/sample/edit_music.jade');
        var html = tmpl({config: config});
        $('#dialog_layer').append(html);
        this.parent = $('#dialog_bgmedit');
        this.parent.show();
        uiUtil.dialogInc();
        var self = this;
        animate.normalScaleIn(this.parent).then(function() {
            self.oldBpm = timing.getPointAt([0,0,4]).bpm;
            $("#dialog_timing_bpm").val(self.oldBpm);
            $("#dialog_timing_offset").val(bgmNote.offset);
            $("#dialog_timing_title").html(bgmNote.sound);
            self.audioFile = note.getFilePath(bgmNote.sound);
            self.oldSample = bgmNote.sound;
            self.bindUIEvent();
        });
    },

    onEvent : function(e, param){
        if(e == event.events.dialog.editmusic){
            this.show();
            return true;
        }
    },

    findBgmNote : function(){
        var chart = note.getNote('main');
        for(var i=0;i<chart.note.length;i++){
            var _note = chart.note[i];
            if(_note.isBgm){
                return _note;
            }
        }
        return null;
    },

    updateMusicInfo : function(){
        var bgmNote = this.findBgmNote();
        if(bgmNote){
            if(this.audioFile){
                var newSample = path.basename(this.audioFile);
                if(this.oldSample != newSample){
                    sample.addSample(this.audioFile);
                    bgmNote.sound = path.basename(this.audioFile);
                    grid.loadSamples();
                    sample.removeSample(this.oldSample);
                }
            }
            bgmNote.offset = parseInt($("#dialog_timing_offset").val());
            sound.offsetCell(bgmNote.tid, bgmNote.offset);
        }
        var newBpm = parseFloat($("#dialog_timing_bpm").val());
        if(this.oldBpm != newBpm){
            timing.change({beat:[0,0,4]}, {bpm: newBpm});
            event.trigger(event.events.grid.bpm);
        }
    },

    stopMusic: function(release){
        sound.fmod.selectTrack(1);
        if(this.playId > -1){
            sound.fmod.pauseTrack();
        }
        if(release){
            sound.fmod.selectCell(this.playCell);
            sound.fmod.removeCell();
            //sound.unload(this.playId);
            this.playId = -1;
            this.playCell = -1;
        }else{
            sound.fmod.seekTrack(0);
        }
    },

    hide : function(){
        if(this.playId != -1){
            this.stopMusic(true);
        }
        var self = this;
        animate.normalScaleOut(this.parent).then(function(){
            self.parent.remove();
            self.parent = null;
            uiUtil.dialogDec();
            sound.fmod.selectTrack(0);
        });
        event.unlock();
        _inited = false;
    }
};



module.exports = ret;